<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="platformOrderNo">
        <el-input
            v-model="queryParams.platformOrderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="invoiceNumber">
        <el-input
            v-model="queryParams.invoiceNumber"
            placeholder="请输入发货单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="contractTele">
        <el-input
            v-model="queryParams.contractTele"
            placeholder="请输入联系人电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="orderCreateTime">
        <el-date-picker clearable
                        v-model="queryParams.orderCreateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择订单创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="afterSalesList" row-key="orderId" @row-click="handleRowClick" @expand-change="handleExpandChange"
               size="small" border>
      <el-table-column type="expand" width="55" align="center">
        <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
        <template #default="scope">
          <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
            <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
              <el-table-column label="商品主图" align="center">
                <template #default="g">
                  <div class="goods-image">
                    <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                              :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" align="center">
                <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
              </el-table-column>
              <el-table-column label="商品规格" align="center">
                <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
              </el-table-column>
              <el-table-column label="商品单价" align="center">
                <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
              </el-table-column>
              <el-table-column label="购买数量" align="center">
                <template #default="g">{{ g.row.count ?? '-' }}</template>
              </el-table-column>
              <el-table-column label="小计" align="center">
                <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无商品" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
      <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
      <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
      <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
      <el-table-column label="优惠券" align="center" prop="couponsId"/>
      <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
      <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
      <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
      <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
      <el-table-column label="联系人电话" align="center" prop="contractTele"/>
      <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
      <el-table-column label="订单状态" align="center" prop="status" width="80px">
        <template #default="scope">
          {{ getOrderStatusText(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getAfterSalesList"
    />

  </div>

</template>

<script setup>
import {getPlatform, listPlatform} from "@/api/order/platform.js";
import {ref, reactive, getCurrentInstance} from "vue";
import {useRouter} from "vue-router";

const { proxy } = getCurrentInstance();
const router = useRouter();
const selectedPlatformId = ref(null)
const afterSalesList = ref([])
const loading = ref(true)
const selectedPlatformRow = ref(null)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const form = ref({})
const total = ref(0)
const showSearch = ref(true)
const expandLoading = reactive({})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  platformOrderNo: null,
  invoiceNumber: null,
  contractTele: null,
  orderCreateTime: null,
  status: 6  // 只查询售后状态的订单
})

function handleQuery() {
  queryParams.value.pageNum = 1
  getAfterSalesList()
}
// 表单重置
function reset() {
  form.value = {
    orderId: null,
    platformOrderNo: null,
    platformOrderDesc: null,
    platformOrderPrice: null,
    realPrice: null,
    count: null,
    sourcesAddress: null,
    invoiceNumber: null,
    remark: null,
    couponsId: null,
    contactName: null,
    contractTele: null,
    contractAddress: null,
    payType: null,
    payTime: null,
    orderEndTime: null,
    status: null,
    orderCreateTime: null,
    orderCompleteTime: null,
    isPrinted: null,
    isAfterSales: null,
    isEvaluate: null,
    goodPrice: null
  }
  proxy.resetForm("platformRef")
}
// 获取售后订单数据
function getAfterSalesList() {
  loading.value = true;
  listPlatform(queryParams.value).then(response => {
    // 如果后端API支持状态过滤和搜索，直接使用返回的数据
    if (response.rows && response.total !== undefined) {
      afterSalesList.value = response.rows;
      total.value = response.total;
    } else {
      // 如果后端API不支持搜索，前端进行过滤
      let filteredData = response.rows ? response.rows.filter(item => item.status === 6) : [];
      
      // 应用搜索过滤
      if (queryParams.value.platformOrderNo) {
        filteredData = filteredData.filter(item => 
          item.platformOrderNo && item.platformOrderNo.includes(queryParams.value.platformOrderNo)
        );
      }
      
      if (queryParams.value.invoiceNumber) {
        filteredData = filteredData.filter(item => 
          item.invoiceNumber && item.invoiceNumber.includes(queryParams.value.invoiceNumber)
        );
      }
      
      if (queryParams.value.contractTele) {
        filteredData = filteredData.filter(item => 
          item.contractTele && item.contractTele.includes(queryParams.value.contractTele)
        );
      }
      
      if (queryParams.value.orderCreateTime) {
        filteredData = filteredData.filter(item => {
          if (!item.orderCreateTime) return false;
          const itemDate = new Date(item.orderCreateTime).toDateString();
          const searchDate = new Date(queryParams.value.orderCreateTime).toDateString();
          return itemDate === searchDate;
        });
      }
      
      total.value = filteredData.length;
      
      // 前端分页计算
      const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
      const endIndex = startIndex + queryParams.value.pageSize;
      afterSalesList.value = filteredData.slice(startIndex, endIndex);
    }
    
    console.log('售后订单列表:', afterSalesList.value);
    console.log('总数:', total.value);
    loading.value = false
  }).catch(error => {
    console.error('获取售后订单列表失败:', error);
    loading.value = false;
    proxy.$modal.msgError('获取售后订单列表失败');
  })
}

// 懒加载展开明细
function handleExpandChange(row) {
  if (!row) return
  if (Array.isArray(row.goodDetils) && row.goodDetils.length > 0) return
  const orderId = row.orderId
  if (!orderId) return
  expandLoading[orderId] = true
  getPlatform(orderId).then(res => {
    const details = res?.data?.goodDetils
    if (Array.isArray(details) && details.length > 0) {
      row.goodDetils = details
    } else {
      row.goodDetils = [{
        goodName: row.platformOrderDesc || '商品',
        goodSize: '默认规格',
        price: row.goodPrice || row.platformOrderPrice || 0,
        count: row.count || 1,
        realPrice: row.realPrice || row.platformOrderPrice || 0,
        image: row.goodsImage || null
      }]
    }
  }).finally(() => {
    expandLoading[orderId] = false
  })
}

// 初始化数据
getAfterSalesList();
// 行点击选中处理函数（单选）
function handleSingleRowSelection(row, selectedId, selectedRow) {
  const orderId = row.orderId
  if (selectedId.value === orderId) {
    // 如果点击的是已选中的行，取消选中
    selectedId.value = null
    selectedRow.value = null
  } else {
    // 选中新行（自动取消之前的选中）
    selectedId.value = orderId
    selectedRow.value = row
  }
}
// 行点击事件 - 全部订单
function handleRowClick(row) {
  handleSingleRowSelection(row, selectedPlatformId, selectedPlatformRow)
  ids.value = selectedPlatformId.value ? [selectedPlatformId.value] : []
  single.value = selectedPlatformRow.value === null
  multiple.value = selectedPlatformRow.value === null
}

function handleUpdate(row) {
  console.log('点击查看详情，行数据:', row);
  reset()
  const _orderId = row.orderId || ids.value
  console.log('订单ID:', _orderId);

  getPlatform(_orderId).then(response => {
    console.log('API响应:', response);
    form.value = response.data

    const orderData = response.data || row;
    console.log('准备传递的数据:', orderData);
    console.log('序列化后的数据:', JSON.stringify(orderData));

    router.push(
        {
          path: '/MallManagement/orderSet/afterSalesDetail',
          query: {
            orderData: JSON.stringify(orderData)
          }
        }
    );
  }).catch(error => {
    console.error('获取订单详情失败:', error);
    // 如果API失败，使用行数据
    console.log('使用行数据作为备选:', row);
    router.push(
        {
          path: '/MallManagement/orderSet/orderDetail',
          query: {
            orderData: JSON.stringify(row)
          }
        }
    );
  })
}

// 订单状态转换函数
function getOrderStatusText(status) {
  const statusMap = {
    1: '待支付',
    2: '待发货',
    3: '已发货',
    4: '已完成',
    5: '已取消',
    6: '售后处理'
  };
  return statusMap[status] || '未知状态';
}

function resetQuery() {
  proxy.resetForm("queryRef");
  // 重置查询参数到初始状态
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    platformOrderNo: null,
    invoiceNumber: null,
    contractTele: null,
    orderCreateTime: null,
    status: 6
  };
  handleQuery();
}
</script>

<style scoped lang="scss">
.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  margin: 0 auto;
}
</style>